﻿namespace AntdUI_HamburgerMenuTabs.Uc
{
    /// <summary>
    /// 汉堡包菜单 + 无标签页面
    /// </summary>
    public partial class HamburgerMenuPage : UserControl
    {
        public HamburgerMenuPage()
        {
            InitializeComponent();

            Load += (s, e) =>
            {
                // 加载菜单折叠/展开状态（用户控件首次显示之后调用，否则宽度计算有问题）
                LoadMenuCollapseStatus();
            };

            panelMenu.Shadow = 5;
            panelMenu.ShadowOpacityAnimation = true;
            panelMenu.ShadowOpacity = 0.2F;
            panelMenu.ShadowOpacityHover = 0.8F;

            panelPage.Shadow = 5;
            panelPage.ShadowOpacityAnimation = true;
            panelPage.ShadowOpacity = 0.2F;
            panelPage.ShadowOpacityHover = 0.8F;

            InitMenu();
        }

        /// <summary>
        /// 设置菜单项
        /// </summary>
        /// <param name="menus"></param>
        public void SetMenu(List<Models.MenuItem>? menus)
        {
            hm1.SetMenu(menus);
        }

        /// <summary>
        /// 手风琴模式：true 每次只能展开一个菜单项；false 可以同时展开多个菜单项
        /// </summary>
        /// <param name="isAccordion"></param>
        public void SetAccordion(bool isAccordion)
        {
            hm1.IsAccordion = isAccordion;
        }

        /// <summary>
        /// MenuItem 选择模式：0=默认，会触发选中页面；1=程序控制菜单选中，不触发选中页面；
        /// </summary>
        private int menuSelectMode = 0;

        /// <summary>
        /// 初始化菜单
        /// </summary>
        private void InitMenu()
        {
            SetMenu(null);

            hm1.SetSplitterMenu(splitter1);

            hm1.Menu.SelectChanged += (s, e) =>
            {
                var item = e.Value;

                if (menuSelectMode == 0)
                {
                    if (item.Tag is Models.MenuItemTag tag)
                    {
                        string title = $"{item.Text}";
                        string path = $"{tag.Path}";
                        string path2 = $"{tag.Path2}";
                        Type? pageType = tag.PageType;

                        LoadPage(title, path, path2, pageType);

                        Properties.Settings.Default.LastMenuPath = path;
                        Properties.Settings.Default.Save();
                    }
                }
            };
        }

        /// <summary>
        /// 加载页面
        /// </summary>
        /// <param name="title"></param>
        /// <param name="path"></param>
        /// <param name="path2"></param>
        /// <param name="pageType"></param>
        private void LoadPage(string title, string path, string path2, Type? pageType)
        {
            bool findInstance = false;

            if (panelPage.Tag is Models.PageTag tag)
            {
                if (string.Equals(tag.MenuPath, path, StringComparison.OrdinalIgnoreCase))
                {
                    findInstance = true;
                }
            }

            if (!findInstance)
            {
                if (panelPage.Controls.Count > 0)
                {
                    if (panelPage.Controls[0] is AntdUI.Panel panelContentOld)
                    {
                        if (panelContentOld.Controls.Count > 0)
                        {
                            if (panelContentOld.Controls[0] is UserControl uc)
                            {
                                // 释放页面资源
                                uc.Dispose();
                                panelContentOld.Dispose();
                            }
                        }
                    }
                }

                panelPage.Controls.Clear();

                panelPage.Tag = new Models.PageTag(path);

                AntdUI.Panel panelContent = new()
                {
                    Dock = DockStyle.Fill,
                };

                if (pageType != null)
                {
                    object[] args = [title, path, path2];
                    UserControl pageContent;
                    try
                    {
                        pageContent = (UserControl)Activator.CreateInstance(pageType, args)!;
                    }
                    catch
                    {
                        pageContent = (UserControl)Activator.CreateInstance(pageType)!;
                    }
                    pageContent.Dock = DockStyle.Fill;
                    panelContent.Controls.Add(pageContent);
                }
                else
                {
                    var alert = new AntdUI.Alert()
                    {
                        TextTitle = "警告",
                        Text = "菜单未配置关联页面！",
                        Icon = AntdUI.TType.Warn,
                        Height = 100,
                        Dock = DockStyle.Top,
                    };
                    panelContent.Controls.Add(alert);
                }

                panelPage.Controls.Add(panelContent);
            }
        }

        public AntdUI.Panel? GetPanelPage()
        {
            return panelPage;
        }

        /// <summary>
        /// 菜单默认选中项
        /// </summary>
        public void MenuSelectDefault()
        {
            hm1.Menu.SelectIndex(0, true);
        }

        /// <summary>
        /// 选中最后一次访问的菜单项并打开页面
        /// </summary>
        /// <returns></returns>
        public bool MenuSelectLast(Control? content = null)
        {
            if (!string.IsNullOrEmpty(Properties.Settings.Default.LastMenuPath))
            {
                try
                {
                    hm1.MenuItemCollapsedAll(null);

                    if (content != null) menuSelectMode = 1;

                    hm1.MenuItemSelectOne($"{Properties.Settings.Default.LastMenuPath}");

                    if (content != null)
                    {
                        var panelPage = GetPanelPage();
                        panelPage?.Controls.Add(content);
                    }

                    return true;
                }
                finally
                {
                    menuSelectMode = 0;
                }
            }
            return false;
        }

        /// <summary>
        /// 加载菜单面板折叠/展开状态
        /// </summary>
        public void LoadMenuCollapseStatus()
        {
            hm1.LoadMenuCollapseStatus();
        }
    }
}